import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TicketDAO {
    /**
     * 添加票务记录
     */
    public static void addTicket(Ticket ticket) {
        String sql = "INSERT INTO tickets (id, show_id, seat_ids, customer_phone, price, purchase_time) " +
                "VALUES (?, ?, ?, ?, ?, ?)";

        // 将座位ID列表转换为逗号分隔的字符串
        String seatIdsStr = String.join(",", ticket.getSeatIds());

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, ticket.getId());
            pstmt.setString(2, ticket.getShowId());
            pstmt.setString(3, seatIdsStr);
            pstmt.setString(4, ticket.getCustomerPhone());
            pstmt.setDouble(5, ticket.getPrice());
            pstmt.setTimestamp(6, new java.sql.Timestamp(ticket.getPurchaseTime().getTime()));

            pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("添加票务记录失败: " + e.getMessage());
            throw new RuntimeException("添加票务记录失败", e);
        }
    }

    /**
     * 根据ID查询票务记录
     */
    public static Ticket getTicketById(String id) {
        String sql = "SELECT * FROM tickets WHERE id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, id);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                String showId = rs.getString("show_id");
                Show show = ShowDAO.getShowById(showId);

                if (show != null) {
                    List<String> seatIds = Arrays.asList(rs.getString("seat_ids").split(","));

                    return new Ticket(
                            rs.getString("id"),
                            show,
                            seatIds,
                            rs.getString("customer_phone"),
                            rs.getDouble("price"),
                            rs.getTimestamp("purchase_time")
                    );
                }
            }
        } catch (SQLException e) {
            System.err.println("查询票务记录失败: " + e.getMessage());
        }
        return null;
    }

    /**
     * 检查场次是否有售票
     */
    public static boolean hasTicketsForShow(String showId) {
        String sql = "SELECT COUNT(*) as count FROM tickets WHERE show_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, showId);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return rs.getInt("count") > 0;
            }
        } catch (SQLException e) {
            System.err.println("查询场次售票情况失败: " + e.getMessage());
        }
        return false;
    }

    /**
     * 删除票务记录
     */
    public static void deleteTicket(String ticketId) {
        String sql = "DELETE FROM tickets WHERE id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, ticketId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("删除票务记录失败: " + e.getMessage());
            throw new RuntimeException("删除票务记录失败", e);
        }
    }

    /**
     * 获取场次的所有票务记录
     */
    public static List<Ticket> getTicketsByShowId(String showId) {
        List<Ticket> tickets = new ArrayList<>();
        String sql = "SELECT * FROM tickets WHERE show_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, showId);
            ResultSet rs = pstmt.executeQuery();

            Show show = ShowDAO.getShowById(showId);
            if (show == null) return tickets;

            while (rs.next()) {
                List<String> seatIds = Arrays.asList(rs.getString("seat_ids").split(","));

                Ticket ticket = new Ticket(
                        rs.getString("id"),
                        show,
                        seatIds,
                        rs.getString("customer_phone"),
                        rs.getDouble("price"),
                        rs.getTimestamp("purchase_time")
                );
                tickets.add(ticket);
            }
        } catch (SQLException e) {
            System.err.println("查询场次票务记录失败: " + e.getMessage());
        }
        return tickets;
    }
}
